<template>
    <div class="upload">
        <el-upload
            action=""
            :http-request="upload"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :before-upload='beforeUpload'
            :file-list="fileList"
            class="upload-demo"
        >
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{file}" class="fileBox">
                <div class="load" v-loading='true' v-show="loadingSet(file)"></div>
                <span class="el-upload-list__item-actions">
                    <span
                        class="el-upload-list__item-preview"
                        @click="handlePictureCardPreview(file)"
                    >
                        <i class="el-icon-zoom-in"></i>
                    </span>
                    <span
                        v-if="!disabled"
                        class="el-upload-list__item-delete"
                        @click="handleRemove(file)"
                    >
                        <i class="el-icon-delete"></i>
                    </span>
                </span>
                <div class="file" v-if="['jpeg','jpg','png'].indexOf(file.name.replace(/.+\./, '')) == -1">
                    <i class="el-icon-document"></i>
                    <span class="name">{{ file.name }}</span>
                </div>
                <div class="image" v-else>
                    <img :src="file.url" alt="">
                </div>
            </div>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
    </div>
</template>

<script>
import request from '@/utils/request'
import fileDownload from "js-file-download";
import {
    fileDownLoad
} from '@/api/baseController'
export default {
    props: {
        iptAttritube: {
            type: Object,
            default: () => {}
        }
    },
    data() {
        return {
            dialogImageUrl: '',
            dialogVisible: false,
            disabled: false,
            fileList: [],
            url: [],
            fileType: [],
            tip: '',
            loading: false,
            removeData: []
        }
    },
    mounted() {
        if(this.iptAttritube.fieldType == 'upload') {
            this.fileType = ['pdf','jpeg','jpg','png','dwt','dwg','dxf','xls','xlsx','docx','doc','pptx','ppt','zip', 'rar']
            this.tip = '只支持上传大小在20mb以内的pdf、jpeg/jpg/png、dwg/dwt/dxf、xlsx/xls、docx/doc、ppt/pptx、zip、rar格式的图片和文件，请重新上传！'
        } else {
            this.fileType = ['jpeg','jpg','png','bmp']
            this.tip = '只支持上传大小在20mb以内的jpeg/jpg/png/bmp格式的图片，请重新上传！'
        }
    },
    methods: {
        upload(param) {
            this.fileList.push(param.file)
            const formData = new FormData() //这一步不能变
            formData.append('file', param.file)
            this.loading = true
            this.$emit('uploadProgres', false)
            this.getUrl(formData).then(res => {
                this.loading = false
                if(res.code == 200) {
                    this.url.push(res.data)
                    let d = []
                    this.fileList.map((item, i) => {
                        d.push({
                            name: item.name,
                            url: this.url[i]
                        })
                    })
                    let value = {
                        value: d.length == 0 ? [] : JSON.stringify(d),
                        state: true
                    }
                    let obj = this.fileList[this.fileList.length - 1]
                    obj.url = this.$global.uploadUrl + res.data
                    this.$set(this.fileList, this.fileList.length - 1, obj)
                    this.$emit('uploadProgres', true)
                    this.$emit('handleChange', value)
                }
            }).catch(error => {
                this.fileList.pop()
                this.loading = false
                this.$emit('uploadProgres', true)
            })
        },
        getUrl(data) {
            return request({
                url: '/base/upload_file',
                method: 'post',
                data,
            })
        },
        // 移除
        handleRemove(file) {
            this.fileList.map((item, i) => {
                if(item.uid == file.uid) {
                    this.removeData.push(this.url[i])
                    this.fileList.splice(i, 1)
                    this.url.splice(i, 1)
                    let d = []
                    this.fileList.map((item, i) => {
                        d.push({
                            name: item.name,
                            url: this.url[i]
                        })
                    })
                    let value = {
                        value: d.length == 0 ? [] : JSON.stringify(d),
                        state: true
                    }
                    this.$emit('handleChange', value)
                    // this.getFileDownload(data, 'del',file.name, i)
                }
            })
        },
        removeSure(t) {
            t == 'cancle' ? this.removeData = [] : ''
            if(this.removeData.length > 0 && t != 'cancle') {
                let data = {
                    type: 'del',
                    path: this.removeData.length > 0 ? this.removeData.join(',') : ''
                }
                this.getFileDownload(data, 'del')
            }
        },
        getFileDownload(data, type, title, index) {
            fileDownLoad(data).then(res => {
                if(type == 'del') {
                    
                } else {
                    fileDownload(
                        res,
                        title, 
                        'application/vnd.ms-excel;charset=UTF-8'
                    )
                }
            })
        },

        // 图片放大/文件下载
        handlePictureCardPreview(file) {
            let FileExt = file.name.replace(/.+\./, "");
            let fileType = ['jpeg','jpg','png','bmp']
            if (fileType.indexOf(FileExt) != -1){
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            } else {
                this.handleDownload(file)
            }
        },

        // 下载 
        handleDownload(file) {
            this.fileList.map((item, i) => {
                if(item.uid == file.uid) {
                    let data = {
                        type: 'download',
                        path: this.url[i]
                    }
                    this.getFileDownload(data, 'download', file.name)
                }
            })
        },

        // 上传文件前校验大小和类型
        beforeUpload(file) {
            let fielSize = file.size / 1024 / 1024
            let FileExt = file.name.replace(/.+\./, "");
            if (this.fileType.indexOf(FileExt) === -1 || fielSize > 20){  
                this.$confirm(this.tip, {
                    confirmButtonText: '好的',
                    showClose:false,
                    type: 'warning'
                }).then(() => {}).catch(e =>{})           
                return false;       
            }
        },

        defaultData(d) {
            this.fileList = []
            d.map(item => {
                if(this.iptAttritube.id == item.customFieldId) {
                    let arr = !Array.isArray(item.value) ? JSON.parse(item.value) : item.value
                    arr.map(k => {
                        this.fileList.push({
                            name: k.name,
                            url: this.$global.uploadUrl + k.url
                        })
                        this.url.push(k.url)
                    })
                    
                }
            })
        },
        loadingSet(f) {
            let d = this.url.find(res => { return this.$global.uploadUrl + res == f.url })
            if(d != undefined) {
                return false
            } else {
                return true
            }
        }
    }
}
</script>

<style lang='less' scoped>
.upload {
    /deep/ .el-upload--picture-card {
        width: 104px;
        height: 104px;
        line-height: 104px;
    }
    /deep/ .el-upload-list__item {
        width: 104px;
        height: 104px;
    }
    .fileBox {
        padding: 8px;
        width: 100%;
        height: 100%;
        position: relative;
        .load {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            z-index: 99;
        }
        .file {
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-wrap: wrap;
            i {
                font-size: 36px;
                color: #5799b9;
            }
            .name {
                font-size: 12px;
                display: inline-block;
                overflow:hidden;
                text-overflow:ellipsis;
                white-space:nowrap; 
                width: 100%;
                text-align: center;
            }
        }
        .image {
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            img {
                width: 100%;
            }
        }
    }
    /deep/ .el-upload-list__item {
        transition: none ;
    }
}
</style>